import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from app import create_app, db
from app.models.user import User

def create_admin(username, password):
    app = create_app()
    
    with app.app_context():
        # 检查用户是否已存在
        if User.query.filter_by(username=username).first():
            print(f"用户 {username} 已存在!")
            return False
            
        # 创建新管理员用户
        admin = User(username=username, user_type='admin')
        admin.set_password(password)
        
        try:
            db.session.add(admin)
            db.session.commit()
            print(f"管理员 {username} 创建成功!")
            return True
        except Exception as e:
            print(f"创建管理员失败: {str(e)}")
            db.session.rollback()
            return False

if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("使用方法: python create_admin.py <username> <password>")
        sys.exit(1)
        
    username = sys.argv[1]
    password = sys.argv[2]
    
    create_admin(username, password) 